<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\models\system\DictData;
use common\models\system\DictType;

class DictService
{
    /**
     * 根据标识获取类型信息
     * @param string $type
     * @return DictType|null
     */
    public static function selectTypeByType(string $type): ?DictType
    {
        if (!$type) return null;
        $info = DictType::findOne(['type' => $type]);
        return $info ?: null;
    }

    /**
     * 根据字典类型查询字典数据
     * @param string $dictType
     * @param false $all
     * @return array
     */
    public static function selectDictDataByType(string $dictType, $all = true): array
    {
        if (!$dictType) return [];
        $query = DictData::find()->where(['type' => $dictType]);
        if (!$all) $query = $query->andWhere(['status' => '1']);
        $list = $query->orderBy('list_sort asc,id asc')->asArray()->all();
        return $list ?: [];
    }

    /**
     * 更新默认值
     * @param DictData $model
     */
    public static function updateDataDefault(DictData $model)
    {
        if ($model->is_default === 'Y') {
            DictData::updateAll(['is_default' => 'N'], ['and', ['type' => $model->type], ['<>', 'id', $model->id]]);
        }
    }
}
